package io.nads.service.impl;

import cn.hutool.core.util.StrUtil;
import io.nads.api.impl.QiniuASR;
import io.nads.api.impl.QiniuUploader;
import io.nads.constant.RedisConstant;
import io.nads.context.BaseContext;
import io.nads.dto.Result;
import io.nads.entity.ChatSession;
import io.nads.entity.UserChatMessage;
import io.nads.mapper.ChatSessionMapper;
import io.nads.service.ChatService;
import io.nads.service.ChatSessionService;
import io.nads.service.ITalkService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import opennlp.tools.stemmer.snowball.finnishStemmer;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
@Slf4j
@RequiredArgsConstructor
public class TalkServiceImpl implements ITalkService {
    private final ChatService chatService;
    private final QiniuUploader qiniuUploader;
    private final QiniuASR qiniuASR;
    private final StringRedisTemplate stringRedisTemplate;
    private final ChatSessionMapper chatSessionMapper;
    private final TTSServiceImpl tTSServiceImpl;

    @Override
    public Result talk(Long chatSessionId, MultipartFile audioFile) {
        log.debug("talk chatSessionId={}", chatSessionId);
        // 更新chatSession缓存以及音色缓存
        if (chatSessionId == null || audioFile == null) {
            return Result.fail("请选择正确的会话或者创建新会话");
        }

        BaseContext.setCurrentSessionId(chatSessionId);

        try {
            // 上传对象到存储容器
            String url = qiniuUploader.upload(audioFile);
            // 调用语音识别
            String text = qiniuASR.parse(url);
            if(StrUtil.isBlank(text)) {
                return Result.fail("说话声音太短了，请尝试");
            }
            UserChatMessage replay = chatService.chat(text);
            String voiceUrl = tTSServiceImpl.getVoiceUrl(replay);
            return Result.ok(voiceUrl);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.fail(e.getMessage());
        }
    }
}
